package cn.deschen.biz.service.impl;

import cn.deschen.biz.domain.entity.AdKeyword;
import cn.deschen.biz.domain.entity.AdUnitKeyword;
import cn.deschen.biz.dto.unit.UnitEleDTO;
import cn.deschen.biz.mapper.AdKeywordMapper;
import cn.deschen.biz.service.AdKeywordService;
import cn.deschen.biz.service.AdUnitKeywordService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 关键词 Feature 服务实现类
 * </p>
 *
 * @author deschen
 * @since 2021-06-15
 */
@Service
public class AdKeywordServiceImpl extends ServiceImpl<AdKeywordMapper, AdKeyword> implements AdKeywordService {

    @Autowired
    private AdUnitKeywordService unitKeywordService;

    @Override
    public void batchUnitRel(Long unitId, Collection<Long> keywordIds) {
        List<AdUnitKeyword> unitKeywordList = keywordIds.stream().map(keywordId -> {
            AdUnitKeyword unitKeyword = new AdUnitKeyword();
            unitKeyword.setUnitId(unitId);
            unitKeyword.setKeywordId(keywordId);
            return unitKeyword;
        }).collect(Collectors.toList());
        unitKeywordService.saveBatch(unitKeywordList);
    }

    @Override
    public Set<Long> listEleIdById(Long unitId) {
        QueryWrapper<AdUnitKeyword> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(AdUnitKeyword::getUnitId, unitId);
        Set<Long> keywordIdSet = unitKeywordService.list(wrapper).stream().map(AdUnitKeyword::getKeywordId).collect(Collectors.toSet());
        return keywordIdSet;
    }

    @Override
    public List<Long> saveBatchKeyword(Long unitId, Collection<UnitEleDTO> unitEleDTOS) {
        List<Long> keywordIdList = new ArrayList<>();
        List<AdKeyword> keywordList = new ArrayList<>();
        unitEleDTOS.stream().forEach(ele -> {
            if (null == ele.getEleId()) {
                AdKeyword keyword = new AdKeyword();
                keyword.setKeywordName(ele.getEleName());
                keywordList.add(keyword);
            }else {
                keywordIdList.add(ele.getEleId());
            }
        });
        saveBatch(keywordList);
        keywordIdList.addAll(keywordList.stream().map(AdKeyword::getId).collect(Collectors.toList()));
        return keywordIdList;
    }
}
